<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/10/23
 * Time: 9:31
 */

namespace app\api\controller;


use JPush\DevicePayload;
use language\Languagemsg;
use think\Db;

class Shopdraw extends Base
{
    private $user_id; // 用户ID
    private $page; // 页码
    private $create_time;
    
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->msg_language = new Languagemsg();
        $this->language = input('language') ? input('language') : 0;
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id, $time, $value, $reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301, 'msg'=>$this->msg_language->otherLogin[$this->language]]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->msg_language->frost[$this->language]]);
            exit;
        }
    }
    
    /**
     * 抽奖列表
     * @return \think\response\Json
     * page    页码
     */
    public function drawList(){
        $list = Db::table('up_draw')
            ->where('draw_user_id', $this->user_id)
            ->field('draw_id, draw_begin_date, draw_end_date, draw_condition')
            ->order('draw_time desc')
            ->page($this->page, 15)
            ->select();
        if($list){
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 添加抽奖
     * @return \think\response\Json
     * draw
     *      draw_explain     抽奖说明
     *      draw_begin_date  抽奖开始时间
     *      draw_end_date    抽奖结束时间
     *      draw_condition   参与条件  1 我的粉丝   2 已购买用户   3 我的粉丝或者已购买用户
     *      draw_info        奖品
     *          di_name      奖品名称
     *          di_image     奖品图片
     *          di_num       奖品数量
     *          di_prob      中奖概率
     */
    public function addDraw(){
        $draw = input('draw');
        $draw = json_decode($draw, true);
        $draw_explain = $draw['draw_explain'];
        $draw_begin_date = $draw['draw_begin_date'];
        $draw_end_date = $draw['draw_end_date'];
        $draw_condition = $draw['draw_condition']; // 1 我的粉丝   2 已购买用户   3 我的粉丝或者已购买用户
        $draw_info = $draw['draw_info']; // 奖品
        $exist = Db::table('up_draw')
            ->where('draw_user_id', $this->user_id)
            ->where('draw_end_date', '>', $draw_begin_date)
            ->find();
        if($exist){
//            return json(['status' => 0, 'msg' => '活动时间有冲突']);
            return json(['status' => 0, 'msg' => $this->msg_language->timeCT[$this->language]]);
        }
        $insert = [
            'draw_user_id' => $this->user_id,
            'draw_explain' => $draw_explain,
            'draw_begin_date' => $draw_begin_date,
            'draw_end_date' => $draw_end_date,
            'draw_condition' => $draw_condition,
            'draw_time' => $this->create_time
        ];
        $date = date('Y-m-d');
        if($draw_begin_date <= $date) $insert['draw_status'] = 2;
        
        Db::startTrans();
        try{
            // 抽奖表
            $draw_id = Db::table('up_draw')->insertGetId($insert);
            // 奖品表
            $info = [];
            $prob = 0; // 概率
            if(is_array($draw_info) && !empty($draw_info)){
                foreach($draw_info as $k => $v){
                    $info[$k] = [
                        'di_draw_id' => $draw_id,
                        'di_name' => $v['di_name'],
                        'di_image' => $v['di_image'],
                        'di_num' => $v['di_num'],
                        'di_prob' => $v['di_prob']
                    ];
                    $prob += $v['di_prob'];
                }
                Db::table('up_draw_info')->insertAll($info);
            }
            if($prob > 100){
//                return json(['status' => 0, 'msg' => '中奖概率不可超过100%']);
                return json(['status' => 0, 'msg' => $this->msg_language->getGL[$this->language]]);
            }
            Db::commit();
//            return json(['status' => 200, 'msg' => '添加成功']);
            return json(['status' => 200, 'msg' => $this->msg_language->addSuccess[$this->language]]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 抽奖详情
     * @return \think\response\Json
     * draw_id    抽奖ID
     */
    public function drawDetail(){
        $draw_id = input('draw_id');
        $draw = Db::table('up_draw')
            ->where('draw_id', $draw_id)
            ->field('draw_id, draw_explain, draw_begin_date, draw_end_date, draw_condition, draw_status')
            ->find();
        // 奖品
        $info = Db::table('up_draw_info')
            ->where('di_draw_id', $draw_id)
            ->field('di_id, di_name, di_image, di_num, di_prob')
            ->select();
        if($info){
            $draw['info'] = $info;
            // 中奖人
            foreach($info as $k => $v){
                $get_user = Db::table('up_my_draw')
                    ->join('up_draw_info', 'di_id = md_draw_info_id', 'LEFT')
                    ->join('up_u_user', 'md_user_id = user_id', 'LEFT')
                    ->where('md_draw_info_id', $v['di_id'])
                    ->where('md_draw_status', 1)
                    ->field('md_user_id, user_image, user_username')
                    ->select();
                if($get_user){
                    $draw['get_user'][$v['di_name']] = $get_user;
                }else{
                    $draw['get_user'][$v['di_name']] = [];
                }
            }
        }else{
            $draw['info'] = [];
            $draw['get_user'] = [];
        }
        return json(['status' => 200, 'msg' => $draw]);
    }
    
    /**
     * 我的中奖纪录
     * @return \think\response\Json
     * page    页码
     */
    public function drawRecord(){
        $record = Db::table('up_my_draw')
            ->join('up_draw_info', 'di_id = md_draw_info_id', 'LEFT')
            ->join('up_draw', 'draw_id = md_draw_id', 'LEFT')
            ->where('md_user_id', $this->user_id)
            ->where('md_draw_status', 1)
            ->field('di_name, di_image, draw_user_id')
            ->order('md_time desc')
            ->page($this->page, 15)
            ->select();
        if($record){
            return json(['status' => 200, 'msg' => $record]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 画师是否有正在进行的抽奖
     * @return \think\response\Json
     * other_user_id    画师ID
     */
    public function haveDraw(){
        $other_user_id = input('other_user_id');
        $data = Db::table('up_draw')
            ->where('draw_user_id', $other_user_id)
            ->where('draw_status', 2)
            ->field('draw_explain, draw_id')
            ->find();
        if($data){
            $have = 1; // 有进行中的抽奖
        }else{
            $have = 2;
        }
        return json(['status' => 200, 'msg' => $have, 'data' => $data]);
    }
    
    /**
     * 抽奖
     * @return \think\response\Json
     * draw_id    抽奖ID
     */
    public function draw(){
        $draw_id = input('draw_id');
        // *****************  判断活动是否结束
        $draw = Db::table('up_draw')
            ->where('draw_id', $draw_id)
            ->field('draw_id, draw_status, draw_condition, draw_user_id')
            ->find();
//        if($draw['draw_status'] == 3) return json(['status' => 0, 'msg' => '活动已结束']);
        if($draw['draw_status'] == 3) return json(['status' => 0, 'msg' => $this->msg_language->acitvityOver[$this->language]]);
        
        // ******************  判断是否符合抽奖条件
        // 画师粉丝
        $fen_ids = Db::table('up_my_attent')->where('att_other_user_id', $draw['draw_user_id'])->column('att_my_user_id');
        // 是否购买过该画师的商品
        $have_order = Db::table('up_goods_order')
            ->where('order_buy_user_id', $this->user_id)
            ->where('order_sail_user_id', $draw['draw_user_id'])
            ->where('order_status', 'IN', '4,9')
            ->where('order_aftersale_status', 2)
            ->find();
        if($draw['draw_condition'] == 1){ // 粉丝
            if(!in_array($this->user_id, $fen_ids)){
//                return json(['status' => 0, 'msg' => '您不符合抽奖条件']);
                return json(['status' => 0, 'msg' => $this->msg_language->notQualify[$this->language]]);
            }
        }elseif($draw['draw_condition'] == 2){ // 购买过商品
            if(!$have_order){
//                return json(['status' => 0, 'msg' => '您不符合抽奖条件']);
                return json(['status' => 0, 'msg' => $this->msg_language->notQualify[$this->language]]);
            }
        }else{
            if(!in_array($this->user_id, $fen_ids) && !$have_order){
//                return json(['status' => 0, 'msg' => '您不符合抽奖条件']);
                return json(['status' => 0, 'msg' => $this->msg_language->notQualify[$this->language]]);
            }
        }
        // 是否已经参加过该活动
        $exist = Db::table('up_my_draw')
            ->where('md_user_id', $this->user_id)
            ->where('md_draw_id', $draw_id)
            ->find();
        if($exist){
//            return json(['status' => 0, 'msg' => '您已参加过该次活动']);
            return json(['status' => 0, 'msg' => $this->msg_language->alreadyApply[$this->language]]);
        }
        
        
        // *****************  抽奖
        $return = $this->getDraw($draw_id);
        
        Db::startTrans();
        try{
            // 如果中奖,奖项中奖人数+1， 插入中奖表
            if($return['di_id'] != -1){
                Db::table('up_draw_info')->where('di_id', $return['di_id'])->setInc('di_get_num');
                $status = 1; // 已中奖
            }else{
                $status = 2; // 未中奖
            }
            Db::table('up_my_draw')->insert([
                'md_user_id' => $this->user_id,
                'md_draw_id' => $draw_id,
                'md_draw_info_id' => $return['di_id'],
                'md_time' => $this->create_time,
                'md_draw_status' => $status
            ]);
            
            // 如果奖品都没有了，该抽奖活动提前结束
            $full = 1; // 1 奖品已抽完  2 没有抽完
            $draw_info = Db::table('up_draw_info')
                ->where('di_draw_id', $draw_id)
                ->field('di_num, di_get_num')
                ->select();
            foreach($draw_info as $k => $v){
                if($v['di_get_num'] < $v['di_num']){
                    $full = 2;
                    break;
                }
            }
            if($full == 1){
                Db::table('up_draw')->where('draw_id', $draw_id)->setField('draw_status', 3);
            }
            Db::commit();
            return json(['status' => 200, 'msg' => $return]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 抽奖
     * @param $draw_id   抽奖ID
     * @return array
     */
    private function getDraw($draw_id){
        $rand_num = rand(1, 1000); // 1~1000，取一个随机数
        $rangeArr = range(1, 1000); // 生成一个1~1000的数组
//        $return = ['di_id' => -1, 'di_name' => '谢谢参与']; // 抽奖结果
        $return = ['di_id' => -1, 'di_name' => $this->msg_language->thinks[$this->language]]; // 抽奖结果
        $drawArr = []; // 抽奖概率数组
        $draw_info = Db::table('up_draw_info')
            ->where('di_draw_id', $draw_id)
            ->field('di_id, di_name, di_image, di_num, di_prob, di_get_num')
            ->select();
        // 踢除已经抽完的奖项
        foreach($draw_info as $k => $v){
            if($v['di_num'] == $v['di_get_num']){
                unset($draw_info[$k]);
            }else{
                $draw_info[$k]['di_prob_big'] = $v['di_prob'] * 10;
            }
        }
        if(empty($draw_info)){ // 都抽完了
            $return['di_id'] = -1;
//            $return['di_name'] = '谢谢参与';
            $return['di_name'] = $this->msg_language->thinks[$this->language];
        }else{
            $max = 999;
            foreach($draw_info as $kk => $vv){
                $ceilArr = [];
                for($i = 0; $i < $vv['di_prob_big']; $i++){
                    $rand_num_choose = rand(0, $max); // 0~999生成一个随机数
                    $ceil = $rangeArr[$rand_num_choose];
                    array_push($ceilArr, $ceil);
                    unset($rangeArr[$rand_num_choose]);
                    $rangeArr = array_values($rangeArr); // 将数组重新排列成索引数组
                    $max--;
                }
                $drawArr[$kk]['di_id'] = $vv['di_id'];
                $drawArr[$kk]['di_name'] = $vv['di_name'];
                $drawArr[$kk]['di_image'] = $vv['di_image'];
                $drawArr[$kk]['rand'] = $ceilArr;
            }
        }
    
        // 生成抽奖结果
        foreach($drawArr as $kkk => $vvv){
            if(in_array($rand_num, $vvv['rand'])){
                $return['di_id'] = $vvv['di_id'];
                $return['di_name'] = $vvv['di_name'];
                $return['di_image'] = $vvv['di_image'];
            }
            break;
        }
        return $return;
    }
}